#include "dbserver.h"
#include "command.h"
#include "bs_def.h"
#include "bs_error.h"


void DBServer::handle(void* arg){
    int fd = getSocketMap(pthread_self());
    BSONObj req = fromjson((char*)arg);
    BSONObj reobj;
    int command = req[REQUEST_TYPE].Int();

    fprintf(stdout, "command[%d] collection[%s]\n", command, req[REQUEST_COLL].String().c_str());
    switch(req[REQUEST_TYPE].Int()){
        case CMD_QUERY:
            reobj = m_mongo.query(req[REQUEST_COLL].String().c_str(), req[REQUEST_QUERY].Obj(), 
                    req[REQUEST_EXTRA].Obj());
            
            if(m_mongo.getLastError()!=""){
                std::cout<<"DB Get Error:"<<m_mongo.getLastError()<<std::endl;
                send(fd, CMD_INSERT_DUP, strlen(CMD_INSERT_DUP), 0);
            }
            else if(reobj.nFields()<=0){
                std::cout<< "Query Result:"<<reobj.toString()<<std::endl;
                send(fd, CMD_NOTFOUND, CMD_STR_LEN, 0);
            }
            else{
                string str = reobj.toString();
                send(fd, str.c_str(), str.length(), 0);
            }
            break;
        case CMD_INSERT:
            m_mongo.insert(req[REQUEST_COLL].String(), req[REQUEST_BODY].Obj()); 
            if(m_mongo.getLastError()!=""){
                std::cout<<"DB Get Error:"<<m_mongo.getLastError()<<std::endl;
                send(fd, CMD_INSERT_DUP, strlen(CMD_INSERT_DUP), 0);
            }
            else{
                send(fd, CMD_SUCCESS, CMD_STR_LEN, 0);
            }

            break;
        case CMD_INDEX:
            //m_mongo.index(req[COLLECTION_NAME].String().c_str(), obj); 
            break;
        case CMD_SORT:
            //m_mongo.sort(req[COLLECTION_NAME].String().c_str(), obj); 
            break;
        case CMD_UPDATE:
            m_mongo.update(req[REQUEST_COLL].String(), req[REQUEST_QUERY].Obj(), req[REQUEST_BODY].Obj(), req[REQUEST_SERT].Bool()); 
            if(m_mongo.getLastError()!=""){
                std::cout<<"DB Get Error:"<<m_mongo.getLastError()<<std::endl;
                send(fd, CMD_INSERT_DUP, strlen(CMD_INSERT_DUP), 0);
            }
            else{
                send(fd, CMD_SUCCESS, CMD_STR_LEN, 0);
            }
            break;
        default:
            int rv = BS_PARAERR;
            send(fd, &rv, sizeof(rv), 0);
            fprintf(stdout, "buf error.\n");
            return;
    }
}

